package com.training1.core.common.schedule;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Aspect
@Component
public class LockTableAop {

	@Resource
	private DataSource dataSource;
	
	private static final Logger log = LoggerFactory.getLogger(LockTableAop.class);
	
	private static final String prefixSQL = "select * from ";
	
	private static final String sufferSQL = " for update";
	
	@Before("@annotation(lockTable)&&@annotation(trx)")
	public void lockTable(LockTable lockTable,Transactional trx) throws SQLException{
		String[] tables = lockTable.tableName();
		Connection connection = DataSourceUtils.doGetConnection(dataSource);
		lock(connection, tables);
	}
	
	private void lock(Connection connection,String[] tables) throws SQLException{
		Statement statement = connection.createStatement();
		for(String t : tables){
			StringBuffer sb = new StringBuffer();
			log.debug("锁表：{}",t);
			String sql = sb.append(prefixSQL).append(t).append(sufferSQL).toString();	
			statement.execute(sql);
		}
	}
	
	
}
